package com.hexacta.hrs.sandbox.tasks2.data;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hexacta.hrs.sandbox.tasks2.model.Activity;
import com.hexacta.hrs.sandbox.tasks2.model.Task;
import com.hexacta.hrs.sandbox.tasks2.model.User;

@SuppressWarnings("unchecked")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	public List<User> findAll() {
		return getHibernateTemplate()
				.find("from " + User.class.getSimpleName());
	}

	public User findById(Long id) {
		User user = (User) getHibernateTemplate().get(User.class, id);
		this.initialize(user);
		return user;
	}

	private void initialize(User user) {
		for (Activity activity : user.getActivities()) {
			activity.getId();
			for (Task task : activity.getTasks()) {
				task.getId();
			}
		}

	}

	public void addUser(User newUser) {
		getHibernateTemplate().save(newUser);

	}

	public User findByName(String name) {
		User user;
		List<User> users = this.getHibernateTemplate().find(
				"from " + User.class.getSimpleName() + " where name = '" + name
						+ "'");

		if (users.iterator().hasNext()) {
			user = users.iterator().next();
			this.initialize(user);
			return user;
		} else {
			return null;
		}
	}

	public void persistUser(User user) {
		this.getHibernateTemplate().saveOrUpdate(user);

	}
}
